# -*- coding: utf-8 -*-
"""
Created on Sat May 11 23:11:52 2024

@author: tuopeng
"""

from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType
import datetime

class ChartGenerator:
    def __init__(self, draw_path="."):
        self.draw_path = draw_path
        self.draw_filename = None

    def draw_time_slicing(self, data, yLabel):
        # 假设dateTimeEdit_andon_start和dateTimeEdit_andon_end是已定义好的获取时间的方法
        start_time = "2023-04-01 00:00:00"
        end_time = "2023-04-10 00:00:00"
        subtitle = f"{start_time} ~ {end_time}"
        
        color_map = {
            0: 'rgb(255,255,255)',
            1: 'rgb(34,177,76)',
            2: 'rgb(255,0,0)',
            # ...其他颜色映射...
           
        }
        
        status_labels = {
            0: 'starve',
            1: 'blocked',
            2: 'machine fault',  # 添加状态值2的描述
            # ...其他状态标签...
                   }
                
        x = [d[0] for d in data]
        ddd = [[d[2][i] for d in data] for i in range(len(data[0][2]))]
       
        
        slicingData = []
        for i, status_row in enumerate(ddd):
            tmp_slices = []
            for j, status in enumerate(status_row):
                # 直接使用内循环的索引j，无需外部循环的索引
                tmp_slices.append([{'value': 1 if k == j else None, 'time': str(yLabel[i]), 'status': status_labels[status], 'sta': x[k]} 
                                  for k, _ in enumerate(x)])
            slicingData.append(tmp_slices)
        
              
        
        c = Bar(init_opts=opts.InitOpts(width="1200px",height="500px",theme=ThemeType.DARK, bg_color="#023560"))
        c.add_xaxis(x)
        
        for i, statuses in enumerate(ddd):
            for j, status in enumerate(statuses):
                c.add_yaxis(
                    status_labels[status],
                    slicingData[i][j],
                    stack="stack1",
                    category_gap="20%",
                    itemstyle_opts=opts.ItemStyleOpts(color=color_map[status], border_color="rgba(0,0,0,0)"),
                )

        c.set_global_opts(
            title_opts=opts.TitleOpts(title='时间切片', pos_left='90px', title_textstyle_opts={'fontSize': 24}, subtitle=subtitle),
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter=lambda x: x)),  # 简化示例，直接显示X轴值
            legend_opts=opts.LegendOpts(is_show=True),
            toolbox_opts=opts.ToolboxOpts(),
            datazoom_opts=[
                opts.DataZoomOpts(type_='inside', range_start=0, range_end=100),
                opts.DataZoomOpts(type_='slider', range_start=0, range_end=100, orient="vertical")
            ],
            tooltip_opts=opts.TooltipOpts(is_show=True),
        )
        
        
        

        c.reversal_axis()
        
        # 修改渲染路径以避免覆盖
        self.draw_filename = f"html/timeSlicing_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.html"
        c.render(self.draw_filename)
        print(f"Chart rendered at: {self.draw_filename}")

# 示例数据
data_example = [
    ["2023-04-01 00:00:00", 0, [1, 2, 0, 1]],  # 时间戳, 无关索引, 状态序列
    ["2023-04-02 01:00:00", 0, [2, 1, 0, 2]],
     ["2023-04-03 01:00:00", 0, [2, 2, 1, 0]],
      ["2023-04-04 01:00:00", 0, [2, 1, 2, 1]],
      ["2023-04-05 01:00:00", 0, [2, 1, 0, 2]],
     ["2023-04-06 01:00:00", 0, [2, 2, 1, 0]],
      ["2023-04-07 01:00:00", 0, [2, 1, 2, 1]],
    # 更多数据...
]

yLabel_example = [datetime.datetime(2023, 4, 1, hour) for hour in range(24)]  # 假设一天的每个小时作为一个切片

chart_gen = ChartGenerator()
chart_gen.draw_time_slicing(data_example, yLabel_example)